import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import { Goods } from '../entities/goods.entity';
import { plainToClass } from 'class-transformer';
import { GoodsAddDTO } from '../dto/goodsAdd.dto';
import { GoodsCategory } from '../entities/goodsCategory.entity';

@Injectable()
export class GoodsService {
  constructor(
    @InjectRepository(Goods)
    private goodsRepository: Repository<Goods>,
    private readonly dataSource: DataSource,
  ) {}

  async getAllGoods(): Promise<Goods[]> {
    const queryBuilder = this.dataSource.createQueryBuilder(Goods, 'goods');
    const result = await queryBuilder
      .leftJoinAndMapOne(
        'goods.categoryInfo',
        GoodsCategory,
        'goodsCategory',
        'goodsCategory.id = goods.categoryId',
      )
      .orderBy('goods.updatedAt', 'DESC')
      .getMany();

    return result;
  }

  async getGoodsById(id: number): Promise<Goods> {
    const queryBuilder = this.dataSource.createQueryBuilder(Goods, 'goods');
    const result = await queryBuilder
      .leftJoinAndMapOne(
        'goods.categoryInfo',
        GoodsCategory,
        'goodsCategory',
        'goodsCategory.id = goods.categoryId',
      )
      .where('goods.id = :id', { id })
      .getOne();
    return result;
  }

  async addGoods(goodsAddDTO: GoodsAddDTO) {
    try {
      const goods = plainToClass(Goods, goodsAddDTO);
      await this.goodsRepository.save(goods);
    } catch (error) {
      console.log(error);
      throw new HttpException('添加商品失败', HttpStatus.BAD_REQUEST);
    }
  }
}
